package leetcode;

/**
 * @创建人 MBY381
 * @创建时间 2022/4/20 19:19
 * @描述 暂无
 */
public class Solution21 {

    /**
     * 正确解法
     * @param l1
     * @param l2
     * @return
     */
    public ListNode mergeTwoLists1(ListNode l1, ListNode l2) {
        ListNode prehead = new ListNode(-1);

        ListNode prev = prehead;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                prev.next = l1;
                l1 = l1.next;
            } else {
                prev.next = l2;
                l2 = l2.next;
            }
            prev = prev.next;
        }

        // 合并后 l1 和 l2 最多只有一个还未被合并完，我们直接将链表末尾指向未合并完的链表即可
        prev.next = l1 == null ? l2 : l1;

        return prehead.next;
    }
    /**
     * 错误解法
     * @param list1
     * @param list2
     * @return
     */
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1==null){
            return list2;
        }else if(list2==null){
            return list1;
        }
        ListNode head = new ListNode();
        if (list1.val <= list2.val) {
            head = list1;
            list1 = swapReturnSmallOne(list1, list2);
        } else {
            head = list2;
            list2 = swapReturnSmallOne(list2, list1);
        }
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                list1 = swapReturnSmallOne(list1, list2);
            }else {
                list2 = swapReturnSmallOne(list2, list1);
            }
        }
        return head;
    }

    public ListNode swapReturnSmallOne(ListNode small, ListNode big) {
        ListNode temp = small.next;
        small.next = big;
        return temp;
    }
}
